/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cart;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author duonghung1369
 */
public class ShoppingCart implements Serializable {

    private float total;
    private int number_of_items;
    private List<ShoppingCartItem> items;

    public ShoppingCart() {
        items = new ArrayList<ShoppingCartItem>();
    }

    /**
     * Add an item to cart.
     * @param item
     */
    public void addToCart(ShoppingCartItem item) {
        ShoppingCartItem i = containItem(item);

        if (i != null) { // just increase amount by 1
            int newAmount = i.getAmount() + 1;
            i.setAmount(newAmount);
        } else { // add new item to cart
            items.add(item);
        }

        number_of_items++;
    }

    public void updateCart(ShoppingCartItem item) {
        ShoppingCartItem i = containItem(item);

        if (i != null) { // just increase quantity
            i.setAmount(item.getAmount());
        }
    }

    /**
     * Delete an item from cart.
     * @param item
     */
    public void deleteFromCart(ShoppingCartItem item) {
        ShoppingCartItem i = containItem(item);

        if (i != null) {
            items.remove(i);
        }
    }

    /**
     * Check cart that had item or not.
     * @param item
     * @return an item if already in cart, null otherwise.
     */
    public ShoppingCartItem containItem(ShoppingCartItem item) {
        for (ShoppingCartItem i : items) {
            if (i.getItem().getId() == item.getItem().getId()) {
                return i;
            }
        }

        return null;
    }

    /**
     * @return the total
     */
    public float getTotal() {
        return total;
    }

    /**
     * @param total the total to set
     */
    public void setTotal(float total) {
        this.total = total;
    }

    /**
     * @return the number_of_items
     */
    public int getNumber_of_items() {
        return number_of_items;
    }

    /**
     * @param number_of_items the number_of_items to set
     */
    public void setNumber_of_items(int number_of_items) {
        this.number_of_items = number_of_items;
    }

    /**
     * @return the items
     */
    public List<ShoppingCartItem> getItems() {
        return items;
    }

    /**
     * @param items the items to set
     */
    public void setItems(List<ShoppingCartItem> items) {
        this.items = items;
    }
}
